import {getInfo, login, logout} from '@/api/auth'
import {getToken, removeToken, setToken} from '@/utils/auth'
// 路由模块当中重置路由的方法
import {resetRouter} from '@/router';

const getDefaultState = () => {
  return {
    // 储存token
    token: getToken(),
    name: '',
    // // 储存用户头像
    avatar: '',
    userInfo: {
      // // 储存用户名
      name: '',
      // // 储存用户头像
      avatar: '',
    },
    // 储存用户角色
    roles: [],
    // 储存用户按钮权限标识
    permissions: [],
    // 储存用户路由
    menus: [],

  }
}

const state = getDefaultState()

const mutations = {
  RESET_STATE: (state) => {
    Object.assign(state, getDefaultState())
  },
  SET_TOKEN: (state, token) => {
    state.token = token
  },
  SET_NAME: (state, name) => {
    state.name = name
  },
  SET_PERMISSIONS: (state, permissions) => {
    state.permissions = permissions
  },

  SET_AVATAR: (state, avatar) => {
    state.avatar = avatar
  },

  SET_USER_INFO: (state, userInfo) => {
    state.userInfo = userInfo
  },
  SET_ROLES: (state, roles) => {
    state.roles = roles // 角色权限
  },
  SET_MENUS: (state, menus) => {
    state.menus = menus // 菜单权限
  }


}

//定义一个函数：两个数组进行对比，对比出当前用户到底显示哪些异步路由
const computedAsyncRoutes = (asyncRoutes, routes) => {
  //过滤出当前用户【超级管理|普通员工】需要展示的异步路由
  return asyncRoutes.filter(item => {
    //数组当中没有这个元素返回索引值-1，如果有这个元素返回的索引值一定不是-1
    if (routes.indexOf(item.name) != -1) {
      //递归:别忘记还有2、3、4、5、6级路由
      if (item.children && item.children.length) {
        item.children = computedAsyncRoutes(item.children, routes);
      }
      return item;
    }
  })
}


const actions = {
  // user login
  async login({commit}, userInfo) {
    const {username, password} = userInfo
    await login({username: username.trim(), password: password}).then(response => {
      const {data} = response
      commit('SET_TOKEN', data)
      setToken(data)
      return "ok";
    }).catch(error => {
      return Promise.reject(new Error("登录失败！"))
    })
  },

  async getInfo({commit}, state) {
    await getInfo().then(response => {
      const {data} = response
      if (!data) {
        return reject('Verification failed, please Login again.')
      }
      data.menuTreeVos.push({'path': '/404', 'component': '404', 'hide': 'true'}, {
        'path': '*',
        'redirect': '/404',
        'hidden': 'true'
      })
      commit('SET_USER_INFO', data)
      commit('SET_NAME', data.userName)
      commit('SET_AVATAR', data.avatar)
      commit('SET_PERMISSIONS', data.permissions)
      commit('SET_ROLES', data.roles) // 角色权限
      commit('SET_MENUS', data.menuTreeVos) // 菜单权限
      return data;
    }).catch(error => {
      return Promise.reject(new Error(error))
    })
  },

  // user logout
  logout({commit, state}) {
    return new Promise((resolve, reject) => {
      logout(state.token).then(() => {
        removeToken() // must remove  token  first
        resetRouter()
        commit('RESET_STATE')
        resolve()
      }).catch(error => {
        reject(error)
      })
    })
  },

  // remove token
  resetToken({commit}) {
    return new Promise(resolve => {
      removeToken() // must remove  token  first
      commit('RESET_STATE')
      resolve()
    })
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}

